<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>format数据</title>
  </head>
  <body>
    <script>
      const formatValue = (size, targetUnit) => {
        const source = {
          BYTE: 1,
          KB: 1024,
          MB: 1024 * 1024,
          GB: 1024 * 1024 * 1024,
        };
        let unit; // 传入的数字中带的单位
        let numReg = /^\d+/g;
        let unitReg = /[a-z|A-Z]+$/g;
        let result; // 结果值
        let transfer; //用来过渡的变量转换
        if (typeof size === "string") {
          unit = size.match(unitReg)?.toString().toUpperCase(); //将size中的单位转成大写
          size = size.match(numReg)?.toString();
        }

        // 先把所有传入的数据转化成字节
        // Object.keys(source).forEach((item, i) => {
        //   if (unit === item) {
        //     size = size * source[item];
        //   }
        // });

        if(unit) {
            size = size * source[unit]
        }
        

        // 如果有目标单位
        if (targetUnit) {
          targetUnit = targetUnit.toUpperCase(); //将目标单位转成大写
        //   Object.keys(source).forEach((item, i) => {
        //     if (targetUnit === item) {
        //       result = size / source[item] + targetUnit;
        //     }
        //   });
          result = size / source[targetUnit] + targetUnit
        }

        // 如果没有目标单位
        if (!targetUnit) {
          Object.keys(source).forEach((item, i) => {
            transfer = size / source[item];
            if (transfer > 1 && transfer <= 1024) {
              result = transfer + item;
            }
          });
        }
        return result;
      };

      console.log(formatValue("10259874"));
      console.log(formatValue("10259874Gb", "KB"));
    </script>
  </body>
</html>
